package com.syyo.admin.config.datasource;

import com.syyo.admin.config.security.config.TokenProvider;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author: wang
 * @date: 2021/8/11 18:16
 * @Description:
 *
 * 膜前没有用到，自定义注解 + AOP的方式实现数据源动态切换。
 */

//@Aspect
//@Component
public class DynamicDataSourceAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TokenProvider tokenProvider;

    @Before("@annotation(DS)")
    public void beforeSwitchDS(JoinPoint point){

        String uri = request.getRequestURI();
        if ("/auth/login".equals(uri)){
            // 用默认的数据源
            DataSourceContextHolder.setDB(DataSourceContextHolder.DEFAULT_DS);
        }else {
            // 用私有的数据源
            // 从token里拿到对应的数据源
            String token = tokenProvider.getToken(request);
            String db = tokenProvider.getDb(token);
            DataSourceContextHolder.setDB(db);
        }
    }

    @After("@annotation(DS)")
    public void afterSwitchDS(JoinPoint point){
        DataSourceContextHolder.clearDB();
    }

}
